<?php

namespace App\Kuafu\CouponPackage\Model;

use App\Kuafu\Activity\Enum\ActivityEnum;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfSplitRelation;
use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\Coupon\Model\CouponModel;
use App\Kuafu\CouponPackage\Enum\CouponPackageEnum;
use App\Kuafu\Customer\Model\CustomerModel;
use App\Kuafu\Order\Model\OrderDetailSplitModel;
use App\Kuafu\Order\Service\OrderDb;
use App\Kuafu\Order\Service\OrderTable;
use App\Kuafu\Pay\Model\PayStreamModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\WaiMai\Model\WaiMaiOrderDetailModel;
use App\Library\SnowFlake\SnowFlake;
use Illuminate\Database\Eloquent\Builder;
use App\Kuafu\Base\Model\BaseModel;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\DB;

class CouponPackageOrderModel extends BaseModel
{
    use KfUid;
    use KfSplitRelation;

    protected $connection = 'mysql';
    protected $table      = 'coupon_package_orders';
    protected $primaryKey = 'orderId';
    protected $fillable   = [
        'orderId',
        'brandId',
        'shopId',
        'userId',
        'couponPackageId',
        'sourceType',
        'payPrice',
        'shopIncomes',
        'payStatus',
        'createdAt',
        'createdByUid',
        'updatedAtByUid'
    ];

    protected $hidden = [
        'updatedAt',
        'isDeleted'
    ];

    const PAY_STATUS_0 = 0; // 待支付
    const PAY_STATUS_1 = 1; // 已支付
    const PAY_STATUS_2 = 2; // 未支付、支付失败

    // 初始化插入订单
    public static function addData(
        int $brandId,
        int $shopId,
        int $userId,
        int $couponPackageId,
        int $sourceType,
        int $payPrice,
        int $shopIncomes,
        int $createdByUid = 0,
        int $updatedByUid = 0
    ): int {
        $orderId   = SnowFlake::nextIdCache();
        $payStatus = self::PAY_STATUS_0;

        self::query()->create(compact('orderId', 'brandId', 'shopId', 'userId', 'couponPackageId', 'sourceType',
            'payPrice', 'shopIncomes', 'payStatus', 'createdByUid', 'updatedByUid'));

        return $orderId;
    }

    /**
     * 支付成功
     * @param int $orderId
     * @return int
     */
    public static function paySuccess(int $orderId)
    {
        return self::query()->where('orderId', $orderId)->update(['payStatus' => self::PAY_STATUS_1]);
    }

    /**
     * 支付失败、超时
     * @param int $orderId
     * @return int
     */
    public static function payFail(int $orderId)
    {
        return self::query()->where('orderId', $orderId)->update(['payStatus' => self::PAY_STATUS_2]);
    }

    /**
     * 检查用户是否购买过券包
     * @param int $userId
     * @param int $couponPackageId
     */
    public static function checkBuyOrder(int $userId, int $couponPackageId): bool
    {
        // 检查用户是否购买过
        return (bool)CouponPackageOrderModel::query()
                                            ->where('userId', $userId)
                                            ->where('couponPackageId', $couponPackageId)
                                            ->where('payStatus', CouponPackageOrderModel::PAY_STATUS_1)
                                            ->count();
    }

    //模型关联
    public function customerRel()
    {
        return $this->hasOne(CustomerModel::class, 'id', 'userId');
    }

    public function shopRel()
    {
        return $this->hasOne(Shop::class, 'id', 'shopId');
    }

    public function couponPackageRel()
    {
        return $this->hasOne(CouponPackageModel::class, 'id', 'couponPackageId');
    }

    /**
     * 在配合get()，使用with时，需要提前设置BaseModel::$splitShopId ！！！！！
     * 使用first()是，不要使用with()
     *
     * @return HasMany
     * @throws \Exception
     */
    public function payStreamRel()
    {
        if (isset($this->shopId) && $this->shopId !== null) {
            self::$splitShopId = $this->shopId;
        }

        $tableName = (new PayStreamModel)->getBaseTable();
        $connect = OrderDb::orderDbConnection(self::$splitShopId);

        return $this->hasManyWithTable(PayStreamModel::class, 'orderId', 'orderId', $tableName, $connect);
    }
}
